import React, { Component } from 'react';
import './form.less';
import BreadcrumbCustom from '../common/BreadcrumbCustom';
import FormTable from './FormTable';
import { message, Button, Modal } from 'antd';
import fetchRequest from '../../fetch/fetchRequest';
import CollectionCreateForm from './CustomizedForm';
import moment from 'moment';
import BillSettlement from './BillSettlement';

// 找到对应元素的索引
function catchIndex(arr, id) { // 获取INDEX
    let index = 0;
    arr.forEach(function (ar, ind) {
        if (ar.id === id) {
            index = ind;
        }
    });
    return index;
}
export default class Order extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dataSource: [],
            loading: true,
            visible: false,
            visibleBill: false,
            formData: { orderNumber: '', orderPrincipal: '', orderCommission: '', orderRemarks: '' },
            // 穿梭框数据
            mockData: [],
            targetKeys: [],
            // 表格选择框
            selectedRowKeys: [],
        };
    }
    // 获取对应用户的订单列表
    getUsersList() {
        const body = { username: this.props.match.params.username }
        fetchRequest.fetchR('orders/username', 'POST', body)
            .then((response) => {
                if (response.length !== 0) { // 该用户的订单不为0
                    response.sort(function (a, b) {
                        return Date.parse(b.orderTime) - Date.parse(a.orderTime);//时间降序
                    });
                    // 按时间分类排序
                    const firstDay = response[0].orderTime.split(' ')[0];
                    const endDay = response[response.length - 1].orderTime.split(' ')[0];
                    // 获得时间间隔数
                    const tempDate = Date.parse(firstDay) - Date.parse(endDay)
                    const iDays = Math.floor(tempDate / (24 * 3600 * 1000));

                    let currenDay = firstDay;
                    // 订单时间数组
                    let orderDayArr = [];
                    let orderHasTime = [];
                    for (let i = 0; i < iDays + 1; i++) {
                        let index = 0;
                        // eslint-disable-next-line no-loop-func
                        response.forEach((item => {
                            let orderTime = item.orderTime.split(' ')[0];
                            if (orderTime === currenDay) {
                                item.index = index + 1;
                                index++;
                                if (index === 1) {
                                    orderHasTime.push(orderTime)
                                }
                            }
                        }))
                        orderDayArr.push(currenDay)
                        currenDay = new Date(Date.parse(currenDay) - 1000 * 60 * 60 * 24).format("yyyy/MM/dd");
                    }
                    this.setState({
                        dataSource: response,
                        loading: false,
                        orderHasTime
                    })
                } else {
                    this.setState({
                        dataSource: response,
                        loading: false,
                        orderHasTime: []
                    })
                }

            }).catch((err) => {  //网络请求失败返回的数据
                message.error('用户数据获取失败')
            });
    }
    // 渲染
    componentDidMount() {
        this.getUsersList();
        this.getSettlement();
    }
    // 通过用户名获得单的id，以便做账单更新
    getSettlement() {
        fetchRequest.fetchR(`settlement/${this.props.match.params.username}`, 'get')
            .then(res => {
                if (res.error === undefined) {
                    this.setState({
                        billId: res.id,
                        noSettlementBill: res.settlementDay
                    })
                }
            }).catch(err => {
                message.error('用户账单数据获取失败!');
            })
    }

    // 接受新建表单数据
    saveFormRef = (form) => {
        this.form = form;
    };
    // 取消
    handleCancel = () => {
        this.setState({ visible: false });
    };
    // 单个删除
    onDelete = (id) => {
        fetchRequest.fetchR(`orders/${id}`, 'delete')
            .then(res => {
                message.success('删除成功!');
                this.getUsersList();
            }).catch(err => {
                message.error('删除失败!');
            })
    };
    // 点击修改
    editClick = (key) => {
        const { dataSource } = this.state;
        const index = catchIndex(dataSource, key);
        this.setState({
            visible: true,
            tableRowKey: key,
            formData: dataSource[index]
        });
    };
    // 更新修改
    handleUpdate = () => {
        const form = this.form;
        const { dataSource, tableRowKey } = this.state;
        form.validateFields((err, values) => {
            if (err) {
                return;
            }

            // 订单号,时间,操作者不变
            const index = catchIndex(dataSource, tableRowKey);
            values.username = dataSource[index].username;
            values.orderTime = dataSource[index].orderTime;
            values.operator = dataSource[index].operator;

            fetchRequest.fetchR(`orders/${tableRowKey}`, 'put', values)
                .then(res => {
                    message.success('更新成功！')
                    this.getUsersList();
                    this.setState({
                        visible: false
                    });
                    form.resetFields();
                }).catch(err => {
                    message.error('更新失败!');
                    this.setState({
                        visible: false
                    });
                    form.resetFields();
                })

            values.id = tableRowKey;
        });
    };

    // 结算相关操作
    showModal = () => {
        const { orderHasTime } = this.state
        this.getSettlement();
        // 获取穿梭框数据
        this.getMock(orderHasTime);

        this.setState({
            visibleBill: true
        })
    }
    modalCancel = () => {
        this.setState({
            visibleBill: false
        })
    }
    modalOk = () => {
        const { mockData, targetKeys, billId } = this.state;
        this.setState({
            visibleBill: false
        })

        //过滤出不被选中的时间,即未结算的时间
        let settlement = mockData.filter((item) => (
            targetKeys.indexOf(item.key) === -1
        ));
        let settlementDay = [];
        for (let i in settlement) {
            settlementDay.push(settlement[i].title)
        }
        const body = {
            username: this.props.match.params.username,
            settlementDay: settlementDay.join(';')
        };
        fetchRequest.fetchR(`settlement/${billId}`, 'put', body)
            .then(res => {
                if (res.error === undefined) {
                    message.success('设置成功！')
                } else {
                    message.error('设置失败！')
                }
            }).catch(err => {
                message.error('设置失败！')
            })
    }
    // 结算的穿梭框数据
    getMock = (orderHasTime) => {
        const { noSettlementBill } = this.state;
        const targetKeys = [];
        const mockData = [];
        for (let i = 0; i < orderHasTime.length; i++) {
            const data = {
                key: i.toString(),
                title: orderHasTime[i],
                chosen: noSettlementBill.indexOf(orderHasTime[i]) === -1,
            };
            if (data.chosen) {
                targetKeys.push(data.key);
            }
            mockData.push(data);
        }
        this.setState({ mockData, targetKeys });
    }

    onRef = (ref) => {
        this.child = ref
    }
    // 选择的订单
    selectedOrders = (selectedRowKeys) => {
        this.setState({ selectedRowKeys });
        if (selectedRowKeys.length === 0) {
            this.setState({
                settlement: false
            })
        }
    }
    // 选中订单结算
    settlement = () => {
        const { selectedRowKeys, dataSource } = this.state;
        if (selectedRowKeys.length === 0) {
            Modal.info({ content: '请选择至少一个订单', okText: '确定' })
        } else {
            let benjin = 0;
            let yongjin = 0;
            dataSource.forEach(item => {
                if (selectedRowKeys.indexOf(item.id) > -1) {
                    benjin += item.orderPrincipal;
                    yongjin += item.orderCommission;
                }
            })
            this.setState({
                benjinSettlement: benjin,
                yongjinSettlement: yongjin,
                settlement: true
            })
        }
    }
    // 清空选择
    start = () => {
        this.setState({
            selectedRowKeys: [],
            settlement: false
        });
    }
    render() {
        const { dataSource, visible, loading, formData, visibleBill, mockData, targetKeys,
            selectedRowKeys, benjinSettlement, yongjinSettlement, settlement } = this.state;
        const today = moment().format("YYYY/MM/DD");
        let count = 0;
        let benjin = 0;
        let yongjin = 0;
        dataSource.forEach(item => {
            let orderTime = item.orderTime.split(' ')[0];
            if (orderTime === today) {
                count = count + 1;
                benjin += item.orderPrincipal;
                yongjin += item.orderCommission;
            }
        })

        const yesterday = new Date(Date.parse(today) - 24 * 60 * 60 * 1000).format("yyyy/MM/dd");
        let count1 = 0;
        let benjin1 = 0;
        let yongjin1 = 0;
        dataSource.forEach(item => {
            let orderTime = item.orderTime.split(' ')[0];
            if (orderTime === yesterday) {
                count1 = count1 + 1;
                benjin1 += item.orderPrincipal;
                yongjin1 += item.orderCommission;
            }
        })

        // 选中的订单数
        const hasSelected = selectedRowKeys.length > 0;
        return (
            <div>
                <BreadcrumbCustom paths={['首页', '用户详情']} />
                <div className='formBody'>
                    <Button type='primary' onClick={this.showModal}>结算</Button>&nbsp;
                    <Button
                        type="primary"
                        onClick={this.start}
                        disabled={!hasSelected}
                    >
                        清空选择
                    </Button>&nbsp;
                    <Button onClick={this.settlement}>对账</Button>
                    <span style={{ marginLeft: 8 }}>
                        {hasSelected ? <span>已选 <span style={{ fontWeight: 'bold' }}>{selectedRowKeys.length} </span>项；</span> : ''}
                        {settlement ? <span>所选订单本金共：<span style={{ fontWeight: 'bold' }}>{parseFloat(benjinSettlement).toFixed(2)}</span>元；
                        佣金共：<span style={{ fontWeight: 'bold' }}>{parseFloat(yongjinSettlement).toFixed(2)}</span>元</span> : ''}
                    </span>

                    <span style={{ float: 'right' }}>
                        今日订单共：<span style={{ fontWeight: 'bold' }}>{count}</span>单；
                        本金：<span style={{ fontWeight: 'bold' }}>{parseFloat(benjin).toFixed(2)}</span>元；
                        佣金：<span style={{ fontWeight: 'bold' }}>{parseFloat(yongjin).toFixed(2)}</span>元
                    </span><br />
                    <span style={{ float: 'right' }}>
                        昨日订单共：<span style={{ fontWeight: 'bold' }}>{count1}</span>单；
                        本金：<span style={{ fontWeight: 'bold' }}>{parseFloat(benjin1).toFixed(2)}</span>元；
                        佣金：<span style={{ fontWeight: 'bold' }}>{parseFloat(yongjin1).toFixed(2)}</span>元
                    </span>
                    <FormTable
                        dataSource={dataSource}
                        onDelete={this.onDelete}
                        editClick={this.editClick}
                        loading={loading}
                        onRef={this.onRef}
                        selectedOrders={this.selectedOrders}
                        selectedRowKeys={selectedRowKeys}
                    />
                    {/* 修改 */}
                    <CollectionCreateForm
                        ref={this.saveFormRef}
                        visible={visible}
                        formData={formData}
                        onCancel={this.handleCancel}
                        onCreate={this.handleUpdate}
                        title="修改信息"
                        okText="更新" />
                    {/* 结算 */}
                    <BillSettlement
                        visible={visibleBill}
                        orderDayArr={mockData}
                        targetKeys={targetKeys}
                        patchBillInfo={(targetKeys) => {
                            this.setState({
                                targetKeys: targetKeys
                            });
                        }}
                        onCancel={this.modalCancel}
                        onOk={this.modalOk}
                        title="账单结算"
                        okText="确定" />
                </div>
            </div>
        )
    }
}